import { useState, useEffect, useCallback } from 'react'
import { useLocation } from 'react-router-dom'
import {
  Form,
  Input,
  Button,
  Upload,
  MessagePlugin,
  Textarea,
  DatePicker,
  UploadProps,
  Row,
  Col,
  Select,
} from 'tdesign-react'
import SearchSelect from '@/components/Form/SearchSelect'
import BMSteps from '../components/BMSteps'
import { useTranslation } from 'react-i18next'
import moment from 'moment'
import { ApiRequest, apis } from '@/service'
import styles from './index.module.less'

type RequestMethodReturn = any

const { FormItem, useForm } = Form

const {
  test: {
    getBugItem,
    insertBugItem,
  },
  system: {
    getDictionaryArray,
  }
} = apis.BMService
const {
  uploadImages
} = apis.CommonService

const CreateBug = (props: any) => {

  const location = useLocation()
  const { t } = useTranslation(['bugManager'])
  const [formRef] = useForm()

  const [id] = useState<string>(location?.state?.id || '')
  const [uploadedImageLink, setUploadImageLink] = useState<string>('')
  const [uploadStatus, setUploadStatus] = useState({
    status: '',
    response: {},
  })
  const [projectName, setProjectName] = useState({ value: '', label: '' })
  const [BUGTYPE, setBUGTYPE] = useState<DictionaryListType>([])
  const [PRIORITY, setPRIORITY] = useState<DictionaryListType>([])

  useEffect(() => {
    queryDictionaryArrayFnc('BugType', setBUGTYPE)
    queryDictionaryArrayFnc('Priority', setPRIORITY)
  }, [])

  useEffect(() => {
    if (id) {
      getBugItemFnc(id)
    }
  }, [id])

  const queryDictionaryArrayFnc = (dictionaryValue: string, setValue: Function) => {
    const params = {
      dictionaryValue,
    }
    ApiRequest({ api: getDictionaryArray, params }).then((res: any) => {
      setValue(res.data)
    })
  }

  const getBugItemFnc = (id: string) => {
    const params = {
      id,
    }
    ApiRequest({ api: getBugItem, params }).then((res: any) => {
      const { code = -1, data = [{}], note = '' } = res
      if (code > 0) {
        formRef.setFieldsValue({
          ...data[0],
          priority: data[0].priority.value,
          bugType: data[0].bugType.value,
          steps: data[0].steps,
          image: data[0].image ? [{
            url: data[0].image,
          }] : undefined
        })
        console.log(formRef.getFieldsValue(true))
      } else {
        MessagePlugin.error({
          content: note,
          placement: 'top-right',
          duration: 2000
        })
      }
    })
  }

  const onSubmit = (context: any) => {
    // 校验成功则运用if逻辑
    if (context.validateResult === true) {
      let params = {
        ...context.fields,
        image: uploadedImageLink,
        createTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        bugType: BUGTYPE.filter(item => item.value === context.fields.bugType)[0],
        priority: PRIORITY.filter(item => item.value === context.fields.priority)[0],
        id,
      }
      ApiRequest({ api: insertBugItem, params: params }).then((res: any) => {
        const { code = -1, data = [], note = '' } = res
        if (code > 0) {
          MessagePlugin.success({
            content: note || '提交成功',
            placement: 'top-right',
            duration: 2000
          })
          formRef.reset()
        } else {
          MessagePlugin.error({
            content: note || '提交失败',
            placement: 'top-right',
            duration: 2000
          })
        }
      })
    } else {
      MessagePlugin.error({
        content: context.firstError,
        placement: 'top-right',
        duration: 2000
      })
    }
  }

  /**
   * 自动生成标题-关联字典改变触发
   * @param value
   * @param context
   */
  const onRelativeFieldsChange = (fieldObject: any, fields: any) => {
    let currentKeys = Object.keys(fieldObject)[0]
    if (!(['projectName', 'moduleName'].includes(currentKeys))) {
      return
    }
    // 当项目名称改变的时候，把这个值存起来，并且传给 extendsInfo
    if (currentKeys == 'projectName') {
      setProjectName({
        label: fields.projectName?.[0]?.label,
        value: fields.projectName?.[0]?.value
      })
      formRef.setFieldsValue({ moduleName: undefined })
    }
    fields = formRef.getFieldsValue(true)
    let projectName = fields.projectName?.[0]?.label
    let moduleName = fields.moduleName?.[0]?.label
    let title = (projectName ? `【${projectName}】` : '') + (moduleName ? `【${moduleName}】` : '')
    formRef.setFieldsValue({
      title: title
    })
  }

  const onFilesChange = async (files: any, context: any) => {
    if (files.length === 0) {
      return
    }
    let fileRaw = files[0].raw
    const params = {
      file: fileRaw,
    }
    ApiRequest({
      api: uploadImages,
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer 716|dkco9DcU6TBH9BOvlofFx909D5dNt8GVsJpeviss',
        'Content-Type': 'multipart/form-data',
      },
      params,
    }).then((res: any) => {
      const { status = 'error', data = [], note = '' } = res
      if (status > 0) {
        MessagePlugin.success({
          content: note || '提交临时文件成功',
          placement: 'top-right',
          duration: 2000
        })
        setUploadImageLink(data.links.url)
        console.log('data', data.links.url)
        setUploadStatus({
          status: 'success',
          response: {
            url: data.links.url
          },
        })
      } else {
        MessagePlugin.error({
          content: note || '提交临时文件失败',
          placement: 'top-right',
          duration: 2000
        })
        setUploadStatus({
          status: 'error',
          response: {
            message: res.message
          },
        })
      }
    }).catch((err: any) => {
      MessagePlugin.error({
        content: err,
        placement: 'top-right',
        duration: 2000
      })
    })
  }

  const requestMethod: UploadProps['requestMethod'] = useCallback(
    () =>
      new Promise<RequestMethodReturn>((resolve) => {
        console.log('uploadStatus', uploadStatus)
        resolve(uploadStatus)
      }),
    [],
  )

  return <div className={`content-wrapper`}>
    <Form
      className='aio-form'
      form={formRef}
      onSubmit={onSubmit}
      labelAlign={'top'}
      onValuesChange={onRelativeFieldsChange}
      resetType='initial'
      initialData={{
        bugType: '1',
        priority: '3',
        steps: [{
          label: '提出',
          value: '0',
        }],
      }}
    >
      <Row gutter={24}>
        <Col span={4}>
          <FormItem name='projectName' label='项目名称' rules={[{ required: true }]}>
            <SearchSelect
              label='项目名称'
              dictionary={'ProjectList'}
              filterKeyList={['label']}
              isCustomize
            />
          </FormItem>
        </Col>
        <Col span={4}>
          <FormItem name='moduleName' label='模块名称' rules={[{ required: true }]}>
            <SearchSelect
              label='模块名称'
              dictionary={'ModuleList'}
              filterKeyList={['label']}
              extendsInfo={{ key: 'projectName.0.value', value: [projectName.value] }}
              isCustomize
            />
          </FormItem>
        </Col>
        <Col span={4}>
          <FormItem label={t(`test.bugType`)} name="bugType" rules={[{ required: true }]}>
            <Select
              clearable
              options={BUGTYPE}
              onChange={onRelativeFieldsChange}
            >
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={4}>
          <FormItem label={t(`test.processor`)} name="processor" rules={[{ required: true }]}>
            <SearchSelect
              label='人员名称'
              dictionary={'UserList'}
              filterKeyList={['label']}
              isCustomize
            />
          </FormItem>
        </Col>
        <Col span={4}>
          <FormItem label={t(`test.priority`)} name="priority" rules={[{ required: true }]}>
            <Select
              clearable
              options={PRIORITY}
            />
          </FormItem>
        </Col>
        <Col span={4}>
          <FormItem label={t(`test.deadline`)} name="deadline">
            <DatePicker
              mode="date"
              presetsPlacement="bottom"
            />
          </FormItem>
        </Col>
      </Row>
      <FormItem label={t(`test.title`)} name="title" rules={[{ required: true }]}>
        <Input
          maxlength={80}
          placeholder="描述问题的标题，最大文本长度为20"
        />
      </FormItem>
      <FormItem label={t(`test.recurrence`)} name="recurrence" >
        <Textarea
          placeholder="请输入内容"
          maxlength={200}
          rows={3}
        />
      </FormItem>
      <FormItem label={t(`test.desireResult`)} name="desireResult" >
        <Textarea
          placeholder="请输入内容"
          maxlength={200}
          rows={3}
        />
      </FormItem>
      <Row gutter={24} style={{ alignItems: 'center' }}>
        <Col span={5}>
          <FormItem label={t(`test.image`)} name="image">
            <Upload
              files={uploadedImageLink ? [{ url: uploadedImageLink }] : undefined}
              onChange={(value: any[], context: any) => { onFilesChange(value, context) }}
              theme="image"
              tips="请选择单张图片文件上传"
              accept="image/*"
              locale={{
                triggerUploadText: {
                  image: '请选择图片',
                },
              }}
              autoUpload={false}
              requestMethod={requestMethod}
            />
          </FormItem>
        </Col>
        <Col span={7}>
          <FormItem label={t(`test.steps`)} name="steps">
            <BMSteps />
          </FormItem>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={6} style={{ textAlign: 'right' }}>
          <Button type="submit" theme="primary">
            提交
          </Button>
        </Col>
        <Col span={6} style={{ textAlign: 'left' }}>
          <Button type="reset" theme="default">
            重置
          </Button>
        </Col>
      </Row>
    </Form>
  </div >
}

export default CreateBug
